from datetime import datetime
from sqlalchemy import Column, Integer, DateTime, String, ForeignKey
from sqlalchemy.orm import relationship
from . import db


class Sqlite3DateTime(db.TypeDecorator):
    """
    解决Sqlite3 在保存datetime类型时抛异常的问题
    """
    impl = DateTime

    def process_bind_param(self, value, dialect):
        if type(value) is str:
            return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S')
        return value


class User(db.Model):
    """
    用户
    """
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment="用户ID")
    username = db.Column(db.String(80), nullable=False, comment="账号")
    password = db.Column(db.String(80), default='123456',
                         nullable=False, comment="密码")
    nickname = db.Column(db.String(80), nullable=False, comment="昵称")
    phone = db.Column(db.String(80), nullable=True, comment="手机号")
    email = db.Column(db.String(80), nullable=True, comment="邮箱")
    lastest_login_time = db.Column(db.DateTime, default=datetime.now(), onupdate=datetime.now(),
                                   nullable=False, comment="最后登录时间")

    def __str__(self):
        return "{}".format(self.username)


class Group(db.Model):
    """
    分组
    """
    __tablename__ = 'group'
    id = Column(Integer, primary_key=True, autoincrement=True, comment="ID")
    title = Column(String(80), comment="标题", nullable=False)
    create_time = Column(DateTime, comment="创建时间",
                         default=datetime.now(), nullable=False)
    update_time = Column(DateTime, comment="更新时间", default=datetime.now(
    ), onupdate=datetime.now(), nullable=False)
    uid = Column(Integer, ForeignKey(User.id))
    user = db.relationship(User, foreign_keys=[uid], backref='groups')

    def __str__(self):
        return "{}".format(self.title)


class Link(db.Model):
    """
    链接
    """
    __tablename__ = 'link'
    id = Column(Integer, primary_key=True, autoincrement=True, comment="ID")

    title = Column(String(80), comment="标题", nullable=False)
    url = Column(String(2048), comment="链接", nullable=False)
    desc = Column(String(256), comment="描述信息", nullable=True)
    create_time = Column(DateTime, comment="创建时间",
                         default=datetime.now(), nullable=False)
    update_time = Column(DateTime, comment="更新时间", default=datetime.now(
    ), onupdate=datetime.now(), nullable=False)

    gid = Column(Integer, ForeignKey(Group.id))
    group = db.relationship(Group, foreign_keys=[gid], backref='links')

    uid = Column(Integer, ForeignKey(User.id))
    user = db.relationship(User, foreign_keys=[uid], backref='u-links')

    def __str__(self):
        return "{}".format(self.title)

# 声明表关系
# Group.links = relationship('Link', order_by=Link.update_time, back_populates="group")

__all__ = ['User', 'Group', 'Link']
